const httpUtils = require('../../utils/httpUtil')

Component({
  properties: {
    // 接收初始的分组和设备数据
    // 格式: [{ id: 'group1', name: 'Group 1', devices: [{ id: 'dev1', name: 'Device 1' }, ...] }, ...]
    initialGroups: {
      type: Array,
      value: [],
      observer: function(newVal) {
        this._initializeData(newVal);
      }
    }
  },

  data: {
    intervalId: undefined,
    groups: [], // 组件内部维护的数据，包含选中状态
    selectedGroupIndex: 0, // 默认选中第一个分组
    selectedDeviceIds: [] // 存储选中的设备 ID
  },

  lifetimes: {
    attached: function() {
      // 组件实例进入页面节点树时执行
      if (!this.data.groups.length && this.data.initialGroups.length) {
        this._initializeData(this.data.initialGroups);
      } else {
        httpUtils.request({
          'method': 'GET',
          'url': '/prod-api/interface/getUserDeptAndDevices',
          'showLoading': true,
          'message': '获取分组设备...'
        }).then(res=>{
          let deptList = [];
          if (res.data.code = 200) {
            for (let dept of res.data.data) {
              console.log('dept==>'+dept);
              deptList.push({
                'id': dept.dept.deptId,
                'name': dept.dept.deptName,
                'devices': dept.deviceList.map(device => {
                  return {
                    'id': device.id,
                    'name': device.deviceName,
                    'number': device.deviceUid,
                    'status': device.onlineStatus,
                  }
                })
              });
            }
          }
          this._initializeData(deptList);
          this._startAutoRefresh();
        });
      }
      this._updateSelectedDeviceIds(); // 初始化选中的设备ID列表
    },

    detached: function() {
      if (this.data.intervalId) {
        clearInterval(this.data.intervalId);
      }
    }
  },

  methods: {
    // 初始化或重置内部数据结构
    _initializeData(initialGroups) {
      const groups = initialGroups.map(group => ({
        ...group,
        selected: false, // 初始分组未选中
        devices: group.devices.map(device => ({
          ...device,
          selected: false // 初始设备未选中
        }))
      }));
      this.setData({
        groups: groups,
        selectedGroupIndex: groups.length > 0 ? 0 : -1 // 默认选中第一个，如果没有则为-1
      });
    },

    // 更新选中的设备ID列表，并触发事件
    _updateSelectedDeviceIds() {
      const selectedDeviceIds = [];
      this.data.groups.forEach(group => {
        group.devices.forEach(device => {
          if (device.selected) {
            selectedDeviceIds.push(device.number);
          }
        });
      });
      this.setData({ selectedDeviceIds });
      this.triggerEvent('change', { selectedDeviceIds });
      console.log('Selected Device IDs:', selectedDeviceIds); // 调试用
    },

    _startAutoRefresh() {
      this.data.intervalId = setInterval(() => {
        console.log('=============刷新分组=============');
        httpUtils.request({
          'method': 'GET',
          'url': '/prod-api/interface/getUserDeptAndDevices',
          'showLoading': false,
        }).then(res=>{
          let deptList = [];
          if (res.data.code = 200) {
            for (let dept of res.data.data) {
              console.log('dept==>'+dept);
              const target = this.data.groups.find(e => e.id === dept.dept.deptId);
              deptList.push({
                'id': dept.dept.deptId,
                'name': dept.dept.deptName,
                'selected': target != undefined ? target.selected : false,
                'devices': dept.deviceList.map(device => {
                  let find = this.data.selectedDeviceIds.find(id => id === device.deviceUid);
                  return {
                    'id': device.id,
                    'name': device.deviceName,
                    'number': device.deviceUid,
                    'status': device.onlineStatus,
                    'selected': find != undefined ? true : false,
                  }
                })
              });
            }

            this.setData({
              groups: deptList,
            });
          }
        });
      }, 60 * 1000);
    },

    // 点击分组名称
    onGroupTap(e) {
      const index = e.currentTarget.dataset.index;
      if (this.data.selectedGroupIndex !== index) {
        this.setData({
          selectedGroupIndex: index
        });
      }
    },

    // 点击分组复选框
    onGroupCheckboxChange(e) {
      const index = e.currentTarget.dataset.index;
      const checked = e.detail.value.length > 0;
      const groupPath = `groups[${index}]`;
      const currentGroup = this.data.groups[index];

      // 更新当前分组下所有设备的选中状态
      const deviceUpdates = {};
      currentGroup.devices.forEach((device, deviceIndex) => {
        console.log('设备状态：'+device.status);
        const devicePath = `${groupPath}.devices[${deviceIndex}].selected`;
        if (device.status == 0) { 
          deviceUpdates[devicePath] = false;
        } else {
          deviceUpdates[devicePath] = checked;
        }
      });

      // 更新分组自身的选中状态
      deviceUpdates[`${groupPath}.selected`] = checked;

      this.setData(deviceUpdates, () => {
        this._updateSelectedDeviceIds(); // 更新选中的设备列表并触发事件
      });
    },

    // 点击设备复选框
    onDeviceCheckboxChange(e) {
      const groupIndex = this.data.selectedGroupIndex;
      const deviceIndex = e.currentTarget.dataset.index;
      const checked = e.detail.value.length > 0;
      const devicePath = `groups[${groupIndex}].devices[${deviceIndex}].selected`;

      this.setData({
        [devicePath]: checked
      }, () => {
        this._updateGroupCheckboxState(groupIndex); // 更新分组复选框状态
        this._updateSelectedDeviceIds(); // 更新选中的设备列表并触发事件
      });
    },

    // 根据设备选中状态更新分组复选框状态
    _updateGroupCheckboxState(groupIndex) {
      const group = this.data.groups[groupIndex];
      if (!group || !group.devices.length) return;

      const allSelected = group.devices.every(device => device.selected);
      const groupSelectedPath = `groups[${groupIndex}].selected`;

      if (this.data.groups[groupIndex].selected !== allSelected) {
        this.setData({
          [groupSelectedPath]: allSelected
        });
      }
    },

    // 供父组件调用的方法，获取当前选中的设备ID
    getSelectedDeviceIds() {
        return this.data.selectedDeviceIds;
    }
  }
});